package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class DwmUserJumpDetailApp_1 extends BaseAppV1 {
    public static void main(String[] args) {
        // ck 和 groupId 要与类名保持一直！！！
        new DwmUserJumpDetailApp_1().init(3002,1,"DwmUserJumpDetailApp_1","DwmUserJumpDetailApp_1", Constant.TOPIC_DWD_PAGE);
    }
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {

        /*stream =  // 示例
                env.fromElements(
                        "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                        "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":11000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000}",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"home\"},\"ts\":18000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"detail\"},\"ts\":50000} "
                );
*/


        KeyedStream<JSONObject, String> keyedStream = stream
                .map(JSON::parseObject)
                // 添加水印
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((page, ts) -> page.getLong("ts")) //事件事件
                )

                .keyBy(page -> page.getJSONObject("common").getString("mid"));

        //1.定义模式 CEP
        // a: 入口 b:紧跟者一个其他的页面
        Pattern<JSONObject, JSONObject> pattern = Pattern
                .<JSONObject>begin("entry")
                .where(new SimpleCondition<JSONObject>() { // 入口
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");

                        return lastPageId == null || lastPageId.length() == 0;
                    }
                })
                .next("normal")
                .where(new SimpleCondition<JSONObject>() { // 非入口 正常访问
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");

                        return lastPageId == null || lastPageId.length() == 0;
                    }
                })
                .within(Time.seconds(5));

        //2.把模式作用在流上
        PatternStream<JSONObject> ps = CEP.pattern(keyedStream, pattern);
        //3.从模式流取出匹配到的数据（超时数据）
        SingleOutputStreamOperator<JSONObject> normal = ps.select(
                new OutputTag<JSONObject>("uj") {},
                new PatternTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject timeout(Map<String, List<JSONObject>> map, long timeoutTimestamp) throws Exception {
                       return map.get("entry").get(0) ;

                    }
                }, new PatternSelectFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject select(Map<String, List<JSONObject>> map) throws Exception {
                        return map.get("entry").get(0) ;
                    }
                }
        );

        normal
                .union(normal.getSideOutput(new  OutputTag<JSONObject>("uj") {}))
                .map(JSONAware::toJSONString)
                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UJ));
    }
}
/*
* dwd_page dwd_start dwd_display
*   消费的topic:
*   选择启动日志，计算的uv值会偏小，对网页，微信等非app启动的无法统计，只有app启动的时候才有启动日志
*
*   选择页面日志：
*
* */